define(['zepto', 'wx', 'sui'], function($, wx) {
    return {
        
        init: function(data) {
          
          var that = this;
          
          var config = data.jsConfig;
          var isDebug = location.search.indexOf('debug=true') > 0
          wx.config({
            debug: isDebug,  //开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: config.appid,
            timestamp: config.timestamp,
            nonceStr: config.nonce_str,
            signature: config.signature,
            jsApiList: ['checkJsApi',
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ',
                        'onMenuShareWeibo']
          });
          
          wx.ready(function(){
            
            var shareJson = {
                title: "陆老师小课堂-口算训练",
                desc:   "来试试娃的口算能力吧~",
                link:   window.__CTX__.domain,
                imgUrl: window.__CTX__.domain + "/resource/images/edooschool.png"
            };
            
            wx.checkJsApi({
              jsApiList: ['onMenuShareTimeline',
                          'onMenuShareAppMessage',
                          'onMenuShareQQ',
                          'onMenuShareWeibo']
            });
            
            wx.onMenuShareAppMessage(
              $.extend({}, shareJson, {"success": 
                function() {
                  window.__CTX__.share(window.__CTX__.root + "/oral-share", {
                    "current": window.location.href,
                    "marks": "口算详情页分享",
                    "type": "朋友"
                  })
                }
              })
            )
            wx.onMenuShareQQ(
              $.extend({}, shareJson, {"success": 
                function() {
                  window.__CTX__.share(window.__CTX__.root + "/oral-share", {
                    "current": window.location.href,
                    "marks": "口算详情页分享",
                    "type": "QQ"
                  })
                }
              })
            )
            wx.onMenuShareWeibo(
              $.extend({}, shareJson, {"success": 
                function() {
                  window.__CTX__.share(window.__CTX__.root + "/oral-share", {
                    "current": window.location.href,
                    "marks": "口算详情页分享",
                    "type": "微博"
                  })
                }
              })
            )

            wx.onMenuShareTimeline({
              title : shareJson.title + "," + shareJson.desc,
              desc: shareJson.desc,
              link:   shareJson.link,
              imgUrl:   shareJson.imgUrl,
              success:  function() {
                window.__CTX__.share(window.__CTX__.root + "/oral-share", {
                  "current": window.location.href,
                  "marks": "口算详情页分享",
                  "type": "朋友圈"
                })
              }
            });
            
          });
          
          that.result = [];
          
          var sources = data.sources;
          
          var ids = that.generateIds(sources);
          
          if(ids.length > 0 && sources.length > 0) {
            
            if(data.refresh === 'true') {
              
              $(".login-warp").addClass("hide");
              that.loopQuestion(ids, sources, data.round);
              $(".real-test").removeClass("hide");
              
            } else {
              
              $(".oral-start-btn").on("click", function(){
                
                $.modal({
                  title: '<h4 class="grade-title">做题须知</h4></a>',
                  afterText: '<p style="background-color: rgba(0,0,0,.7); color: #fff; margin: 0;padding: 1rem .5rem; font-size: .7rem;">请家长口述算式，孩子口算回答。</p>',
                  buttons: [
                    {
                      text: '确定',
                      onClick: function() {
                        $(".login-warp").addClass("hide");
                        that.loopQuestion(ids, sources, data.round);
                        $(".real-test").removeClass("hide");
                      }
                    }
                  ],
                  extraClass: 'grade-modal'
                })
              })
              
            }
            
          }else {
            console.log("init data faild here");
          }
        },

        generateIds: function(sources) {
          var ids = [];
          for(var i in sources) {
            ids.push(sources[i].id);
          }
          return ids;
        },
        
        loopQuestion: function(ids, sources, round) {
          
          var that = this;
          
          var clock = this.clock();
          var index = ids.indexOf(round.start);
          
          // 开始计时
          that.currentTime = 0;
          clock.start(sources[index].value, ids[index]);
          
          // handle btn click
          $(document).on('click', '.selector', function(event) {
            event.preventDefault();
            
            // 如果当前index是最后一个，执行clock的Stop, 提交ajax逻辑，并弹出结果。
            if(ids[index] == round.end && !$(event.currentTarget).prop("disabled")) {
              
              var state = $(event.currentTarget).data("selector") ? true : false;
              
              var currentSeconds = clock.stop();
              var seconds = parseInt(currentSeconds) - parseInt(that.currentTime);
              that.currentTime = parseInt(currentSeconds);
              that.addResult(ids[index], sources[index].value, state, sources[index].branch_start, sources[index].branch_end, seconds);
              
              $(event.currentTarget).prop("disabled", true);
              $("a.button.selector").find(".seconds").html("0");
              $("a.button.selector").data("selector", true).removeClass("button-danger");
              
              that.submitForm(sources, round);
            
            // 不是最后一个，如果通过，通过rebuild方法，记录用时second。下一个id是通过的id, index为这个id的index
            } else if((sources[index].id != round.end)  && $(event.currentTarget).data("selector")) {  
              
              var successIndex = ids.indexOf(sources[index].success_id);
              var currentSeconds = clock.rebuild(sources[successIndex].value, ids[successIndex]);
              var seconds = parseInt(currentSeconds) - parseInt(that.currentTime);
              var state = $(event.currentTarget).data("selector") ? true : false;
              
              that.currentTime = parseInt(currentSeconds);
              that.addResult(ids[index], sources[index].value, state, sources[index].branch_start, sources[index].branch_end, seconds);
              index = successIndex;
              
              $("a.button.selector").find(".seconds").html("0")
              $("a.button.selector").removeClass("button-danger").data("selector", true);
              
              
            } else if((sources[index].id != round.end) && !$(event.currentTarget).data("selector")) {
              
              var failIndex = ids.indexOf(sources[index].fail_id);
              var currentSeconds = clock.rebuild(sources[failIndex].value, ids[failIndex]);
              
              var seconds = parseInt(currentSeconds) - parseInt(that.currentTime);
              var state = $(event.currentTarget).data("selector") ? true : false;
              
              $("a.button.selector").find(".seconds").html("0")
              $("a.button.selector").removeClass("button-danger").data("selector", true);
              
              that.currentTime = parseInt(currentSeconds);
              that.addResult(ids[index], sources[index].value, state, sources[index].branch_start, sources[index].branch_end, seconds);
              index = failIndex;
              
            }
          });
        },
        
        addResult: function(id, value, state, branchStart, branchEnd, seconds) {
          var that = this;
          var item = {
            "id": id,
            "value": value,
            "seconds": seconds,
            "success": state,
            "branchStart": branchStart,
            "branchEnd": branchEnd
          }
          that.result.push(item);
        },
        
        submitForm: function(sources, round) {
          
          var that = this;
          
          var $form = '<form id="resultSubmit" method="POST" action="'+ window.__CTX__.root + '/rounds/' + round.id + '">';
          
          var successTotal    = 0,
              failTotal       = 0,
              branchTotal     = 0;
          
          for(var i in that.result) {
            that.result[i].success ? successTotal++ : failTotal++;
            that.result[i].branchStart ? branchTotal++ : null;
            $form = $form + '<input name="questionResults[' + i + '].id"          value="'+that.result[i].id+'" />';
            $form = $form + '<input name="questionResults[' + i + '].value"       value="'+that.result[i].value+'" />';
            $form = $form + '<input name="questionResults[' + i + '].state"       value="'+that.result[i].success+'" />';
            $form = $form + '<input name="questionResults[' + i + '].branchStart" value="'+that.result[i].branchStart+'" />';
            $form = $form + '<input name="questionResults[' + i + '].branchEnd"   value="'+that.result[i].branchEnd+'" />';
            $form = $form + '<input name="questionResults[' + i + '].seconds"     value="'+that.result[i].seconds+'" />';
          }
          
          $form = $form + '<input name="successCount" value="'+successTotal+'" />';
          $form = $form + '<input name="failCount" value="'+failTotal+'" />';
          $form = $form + '<input name="branchTotal" value="'+branchTotal+'" />';
          $form = $form + '<input name="seconds" value="'+that.currentTime+'" />';
          
          $form = $form + '</form>';
          
          $(document).find("body").append($form);
          
          $("#resultSubmit").submit();
        },
        
        clock: function() {
          
          var that = this;
          var second = 0,
              minute  = 0,
              currentClock;
          
          function start(value, id) {
            $(".question-viewer").html(value).data("question-id", id);
            
            currentClock = setInterval(function() {
              second++;
              if(second > 59) {
                minute++;
                second = 0;
              }
              var minuteString = minute >= 10 ? minute : '0' + minute;
              var secondString = second >= 10 ? second : '0' + second;
              
              clockHtml = '<span class="minute">'+ minuteString +'</span>:' + '<span class="second">' + secondString +'</span>';
              $(".clock").html(clockHtml)
              
              var currentSeconds = minute * 60 + second;
              var durings = parseInt(currentSeconds) - parseInt(that.currentTime);
              
              if(durings >= 4) {
                $("a.button.selector").addClass("button-danger").data("selector", false);
              }
              
              $("a.button.selector").find(".seconds").html(durings);
              
            },1000);
          }
          
          function rebuild(value, id) {
            var stopSecond = minute * 60 + second;
            $(".question-viewer").html(value).data("question-id", id);
            return stopSecond;
          }
          
          function stop() {
            var stopSecond = minute * 60 + second;
            minute = 0;
            second = 0;
            
            clearInterval(currentClock);
            return stopSecond;
          }
          
          return {
            start: start,
            rebuild: rebuild,
            stop: stop
          }
        }
    }
})


